package cn.yunhe.controller;

import cn.yunhe.model.Result;
import cn.yunhe.model.User;
import cn.yunhe.service.IUserService;
import com.github.pagehelper.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by zs on 2017/10/30.
 */
@RestController
public class UserController {

    @Resource
    private IUserService userService;


    @RequestMapping("/login")
    public ModelAndView toLogin() {
        return new ModelAndView("login");
    }

    @RequestMapping("/userLogin")
    public ModelAndView userLogin(User user, HttpSession session, Model model) {
        Integer flag = userService.selectByNameAndPwd(user);
        if (flag != null) {
            session.setAttribute("user", user);
            return new ModelAndView("list");
        } else {
            return new ModelAndView("login");
        }
    }

    @RequestMapping("/userlist")
    public String findAll(Model model) {
        List<User> list = userService.selectAll();
        model.addAttribute("list", list);
        return "list";
    }

    @RequestMapping("/getPage")
    public Map queryUserByPage(int pageNum, int pageSize, User user) {
        Map map = new HashMap();
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        map.put("user", user);

        Page page = userService.queryLikeUsers(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());

        return map;
    }

    @RequestMapping("/add")
    public Result addUser(User user) {
        userService.addUser(user);
        return new Result();
    }

    @RequestMapping("/del")
    public Result delUser(User user) {
        userService.delUser(user);
        return new Result();
    }

    @RequestMapping("/editpage")
    public ModelAndView findUser(User user) {
        User u = userService.getUser(user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", map);
        return new ModelAndView("edit", map);
    }


    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
